package io.renren.modules.sys.controller;

import com.aliyun.oss.common.utils.DateUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import io.renren.common.utils.AesUtil;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
public class SysLoginController {
	@Autowired
	private Producer producer;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	
	@Autowired
	private SysUserEntity enti;
	
	
	//创建全局map用来保存用户登录错误次数信息
	private Map<String, Integer> maps=new HashMap<>() ;
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 * @throws ParseException
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String, Object> login(String users)throws IOException, ParseException {
		try{
			//解密user
			String aesUser = AesUtil.aesDecrypt(users.replaceAll(" ","+"));
			//获取第一个“=”的位置
			int index1 = aesUser.indexOf("=");
			//获取第二个“=”的位置
			int index2 = aesUser.indexOf("=", index1 + 1);
			//获取第三个“=”的位置
			int index3 = aesUser.indexOf("=", index2 + 1);
			//获取第一个“&”的位置
			int index4 = aesUser.indexOf("&");
			//获取第二个“&”的位置
			int index5 = aesUser.indexOf("&", index4 + 1);
			//截取用户名
			String username = aesUser.substring(index1+1, index4);
			//截取密码
			String password = aesUser.substring(index2+1, index5);
			//截取验证码
			String captcha = aesUser.substring(index3+1);
			String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
			//判断map是否为空如为空即为第一次登录
			if(maps==null ||maps.size()<1) {
				maps.put(username, Integer.parseInt(enti.getPasswordSum()));
			}
			if(!captcha.equalsIgnoreCase(kaptcha)){
				return R.error("验证码不正确");
			}
			//用户信息
			SysUserEntity user = sysUserService.queryByUserName(username);
			//账号不存在、密码错误
			System.out.println("用户输入   ："+new Sha256Hash(password, user.getSalt()).toHex());
			System.out.println("数据库  ："+user.getPassword());
			if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
				//错误一次减一次机会
				maps.put(username, maps.get(username)-1);
				//判断密码错误次数是否超过三次
				if(maps.get(username)<=0) {
					//修改用户状态
					sysUserService.updateStatus(username);
					return R.error("您的账号已被冻结！");
				}
				return R.error("账号或密码不正确，您还有"+maps.get(username)+"次机会");
			}
			//账号锁定
			if(user.getStatus() == 0){
				return R.error("账号已被锁定,请联系管理员");
			}
			//生成token，并保存到数据库
			R r = sysUserTokenService.createToken(user.getUserId());
			return r;
		}catch (Exception e){
			return R.error("未知异常，请联系管理员");
		}
	}
}
